package com.teach;

import java.util.Arrays;

/**
 * <pre>
 * - 
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-4-14 10:03:40
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 *
 */
public class Demo01 {

	public static void main(String[] args) {

		String str = toHexString(1);
		System.out.println(str);
		str = toHexString(15);
		System.out.println(str);
		str = toHexString(16);
		System.out.println(str);
		str = toHexString(17);
		System.out.println(str);
		str = toHexString(17123123);
		System.out.println(str);
//		str = toHexString(Long.MAX_VALUE);//报错
//		System.out.println(str);
//		str = toHexString(Long.MIN_VALUE);//报错
//		System.out.println(str);
		str = toHexString(0);// 最小值
		System.out.println(str);
		str = toHexString(0xFFFFFFFFFFFFL);// 最大值
		System.out.println(str);

		long num = toLong("000000000001");// 1
		System.out.println(num);
		num = toLong("000000000000");// 0
		System.out.println(num);
		num = toLong("FFFFFFFFFFFF");// ?
		System.out.println(num);
		num = toLong("00000000000f");// 15
		System.out.println(num);
		num = toLong("000000000010");// 15
		System.out.println(num);

//		num = toLong("FF");//报错
//		System.out.println(num);

		num = toLong("RRRRRRRRRRRR");// 报错
		System.out.println(num);

	}

	/**
	 * - 将num转换成16进制表示的字符串(12位)
	 * 
	 * @param num
	 * @return
	 * @throws RuntimeException 输入参数不能为负数,输入参数超出范围
	 */
	public static String toHexString(long num) {
		// 1. 输出参数的校验
		if (num < 0) {
			throw new RuntimeException("输入参数不能为负数");
		}

		if (num > 0xFFFFFFFFFFFFL) {
			throw new RuntimeException("输入参数超出范围");
		}

		// 2. 核心处理逻辑
//		String.format是非线程安全的 +synchronized
		String ret = String.format("%12s", Long.toString(num, 16)).replace(' ', '0');

//		String ret = "000000000000"+Long.toString(num,16);
//		ret = ret.substring(ret.length()-12);

//		String ret = Long.toString(num,16);
//		char[] cs = new char[12-ret.length()];
//		Arrays.fill(cs, '0');
//		ret = new String(cs)+ret;
		return ret;
	}

	/**
	 * - 将16进制表示的字符串(12位)转成长整型
	 * 
	 * @param str
	 * @return
	 * @throws RuntimeException 输入的字符串长度不等于12,输入的字符串不是16进制的字符
	 */
	public static long toLong(String str) {
		if (str.length() != 12) {
			throw new RuntimeException("输入的字符串长度不等于12");
		}

		try {
			return Long.valueOf(str, 16);
		} catch (Exception e) {
			throw new RuntimeException("输入的字符串不是16进制的字符", e);
		}
	}
}
